package com.wl156.activities.find;

import java.io.IOException;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.mobclick.android.MobclickAgent;
import com.wl156.MyApp;
import com.wl156.R;
import com.wl156.adapters.PlaceAdapter;
import com.wl156.model.Certificate;
import com.wl156.model.WebServiceClient;

public class FindPlace extends Activity implements OnClickListener,
		OnItemClickListener {

	protected static final String TAG = null;

	private PlaceAdapter mAdapter;

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;

	private Spinner mType;
	private EditText mRadius;
	private ListView mList;
	private Button mConfirm;

	private String myLongitude = "";
	private String myLatitude = "";
	private String radius;
	private String mapType;

	LocationManager locationManager;

	TextView mCurrentLocation;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		MobclickAgent.onError(this);
		setContentView(R.layout.act_find_place);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		mList = (ListView) findViewById(R.id.list);
		mList.setOnItemClickListener(this);
		mType = (Spinner) findViewById(R.id.find_kind);
		mRadius = (EditText) findViewById(R.id.radius);
		mConfirm = (Button) findViewById(R.id.confirm);
		mConfirm.setOnClickListener(this);

		mCurrentLocation = (TextView) findViewById(R.id.currentLocation);

		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		// mConfirm.setText("定位中，请稍候");

		List<String> providers = locationManager.getProviders(true);

		// String providers = Settings.Secure.getString(getContentResolver(),
		// Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		// // 03-10 22:39:58.207: E/AndroidRuntime(20101): Caused by:
		// // java.lang.IllegalArgumentException: provider=network,gps
		// String[] items = providers.split(",");
		for (String item : providers) {
			Location loc = locationManager.getLastKnownLocation(item);
			if (loc != null) {
				myLatitude = String.valueOf(loc.getLatitude());
				myLongitude = String.valueOf(loc.getLongitude());
			}
			updateCurrentLocationView(myLatitude, myLongitude);
		}

		openGPSSettings();
	}

	private void updateCurrentLocationView(String lat, String lon) {
		try {
			mCurrentLocation.setText(String.format("当前位置: 纬度: %.3f, 精度: %.3f",
					Double.valueOf(lat), Double.valueOf(lon)));
		} catch (Exception e) {
		}
	}

	private static final int GPS_FAILED = 0;
	private static final int NETWORK_FAILED = 1;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			// case GPS_FAILED:
			// if (TextUtils.isEmpty(myLongitude)) {
			// locationManager.removeUpdates(locationListener);
			// startFetchingLocation(LocationManager.NETWORK_PROVIDER);
			// }
			// break;
			case NETWORK_FAILED:
			default:
				try {
					if (TextUtils.isEmpty(myLongitude)) {
						// locationManager.removeUpdates(locationListener);
						// Toast.makeText(FindPlace.this, "定位失败",
						// Toast.LENGTH_LONG)
						// .show();
						AlertDialog.Builder builer = new AlertDialog.Builder(
								FindPlace.this);
						builer.setMessage("定位失败，请您确保你已经连接网络或者已经开启GPS");
						builer.setNegativeButton("知道了", null);
						builer.show();
					}
				} catch (Exception e) {
				}
				break;
			}
		}
	};

	LocationListener locationListener = new MyLocationListener();
	LocationListener locationListener1 = new MyLocationListener();

	class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
			Log.d(TAG, "location.longitude: " + location.getLongitude()
					+ ", latitude: " + location.getLatitude());
			myLongitude = String.valueOf(location.getLongitude());
			myLatitude = String.valueOf(location.getLatitude());
			updateCurrentLocationView(myLatitude, myLongitude);
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.d(TAG, "onStatusChanged: provider: " + provider + ", status: "
					+ status);
		}

		public void onProviderEnabled(String provider) {
			Log.d(TAG, "onProviderEnabled");
		}

		public void onProviderDisabled(String provider) {
			Log.d(TAG, "onProviderDisabled");
		}
	};

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);

	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	private void startFetchingLocation() {
		// LocationManager.GPS_PROVIDER
		// LocationManager.NETWORK_PROVIDER;
		// String providers = Settings.Secure.getString(getContentResolver(),
		// Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		// // 03-10 22:39:58.207: E/AndroidRuntime(20101): Caused by:
		// // java.lang.IllegalArgumentException: provider=network,gps
		// String[] items = providers.split(",");

		List<String> providers = locationManager.getProviders(true);

		// String providers = Settings.Secure.getString(getContentResolver(),
		// Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		// // 03-10 22:39:58.207: E/AndroidRuntime(20101): Caused by:
		// // java.lang.IllegalArgumentException: provider=network,gps
		// String[] items = providers.split(",");
		for (String item : providers) {
			locationManager.requestLocationUpdates(item, 0, 0,
					new MyLocationListener());
			mHandler.sendMessageDelayed(
					Message.obtain(mHandler, NETWORK_FAILED), 5000);
		}

		// locationManager
		// .requestLocationUpdates(provider, 0, 0, locationListener);
		// if (provider.equals(LocationManager.GPS_PROVIDER)) {
		// mHandler.sendMessageDelayed(Message.obtain(mHandler, GPS_FAILED),
		// 4000);
		// } else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
		// mHandler.sendMessageDelayed(
		// Message.obtain(mHandler, NETWORK_FAILED), 2000);
		// }
	}

	private void openGPSSettings() {
		LocationManager alm = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, "GPS已经开启", Toast.LENGTH_SHORT).show();

			startFetchingLocation();
		} else {
			AlertDialog.Builder builer = new Builder(this);
			builer.setMessage("GPS尚未开启，前去开启？");
			builer.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent myIntent = new Intent(
									Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							startActivityForResult(myIntent, 0);
						}
					});
			builer.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							startFetchingLocation();
						}
					});
			builer.show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(TAG, "requsetCode: " + requestCode + ", resultCode: "
				+ resultCode);
		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		if (provider != null) {
			Log.v(TAG, " Location providers: " + provider);
			// 03-10 22:39:58.207: E/AndroidRuntime(20101): Caused by:
			// java.lang.IllegalArgumentException: provider=network,gps

			if (provider.contains("gps")) {
				startFetchingLocation();
			} else if (provider.contains("network")) {
				startFetchingLocation();
			}
		} else {
			Toast.makeText(this, "无法获取到您的位置，请开启GPS或者网络", Toast.LENGTH_SHORT)
					.show();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.confirm:
			if (TextUtils.isEmpty(myLongitude) || TextUtils.isEmpty(myLatitude)) {
				Toast.makeText(this, "还没有获取到您当前的位置，请稍候再试", Toast.LENGTH_LONG)
						.show();
				return;
			}
			radius = mRadius.getText().toString();
			if (TextUtils.isEmpty(radius)) {
				Toast.makeText(this, "请填写查找半径", Toast.LENGTH_LONG).show();
				return;
			}
			switch (mType.getSelectedItemPosition()) {
			case 0:
				mapType = "A";
				break;
			case 1:
				mapType = "S";
				break;
			case 2:
				mapType = "D";
				break;
			}

			new AsyncTask<Void, Void, Object>() {
				ProgressDialog mDialog;

				@Override
				protected void onPreExecute() {
					mDialog = ProgressDialog.show(FindPlace.this, "", "查找中");
				};

				@Override
				protected void onPostExecute(Object result) {
					if (result instanceof SoapObject) {
						SoapObject so = (SoapObject) result;
						mAdapter = new PlaceAdapter(FindPlace.this, so);
						mList.setAdapter(mAdapter);
					} else {
						Toast.makeText(FindPlace.this, "联网失败，请稍候再试",
								Toast.LENGTH_LONG).show();
					}
					mDialog.dismiss();
				};

				@Override
				protected Object doInBackground(Void... params) {
					try {
						return mWebServiceClient.commonFindMapLocation(
								mCertificate, myLongitude, myLatitude, radius,
								mapType);
					} catch (IOException e) {
						return e;
					} catch (XmlPullParserException e) {
						return e;
					}
				}
			}.execute();
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent i = new Intent(FindPlace.this, PlaceInfo.class);
		i.putExtra("id", mAdapter.getItemId(position));
		SoapObject so = mAdapter.getItem(position);
		i.putExtra("name", so.getPropertyAsString(1));
		i.putExtra("type", so.getPropertyAsString(2));
		i.putExtra("business", so.getPropertyAsString(3));
		i.putExtra("phone", so.getPropertyAsString(4));
		i.putExtra("longitude", so.getPropertyAsString(5));
		i.putExtra("latitude", so.getPropertyAsString(6));
		i.putExtra("radius", so.getPropertyAsString(7));
		startActivity(i);
	}
}
